<?php
declare(strict_types=1);

namespace app\model;

use think\Model;

class MerchantFundFlow extends Model
{
    protected $autoWriteTimestamp = true;

    // 资金流水类型常量
    const TYPE_RECHARGE = 1; // 充值
    const TYPE_WITHDRAW = 2; // 提现
    const TYPE_ORDER_PAY = 3; // 订单支付
    const TYPE_ORDER_REFUND = 4; // 订单退款
    const TYPE_COMMISSION = 5; // 分佣

    // 类型文字说明
    public static $typeTexts = [
        self::TYPE_RECHARGE => '充值',
        self::TYPE_WITHDRAW => '提现',
        self::TYPE_ORDER_PAY => '订单支付',
        self::TYPE_ORDER_REFUND => '订单退款',
        self::TYPE_COMMISSION => '分佣'
    ];

    // 关联商家
    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    // 获取类型文字
    public function getFundFlowTypeTextAttr()
    {
        return self::$typeTexts[$this->fund_flow_type] ?? '未知';
    }

    // 记录资金流水
    public static function record(
        int $merchantId,
        int $type,
        string $orderNo,
        float $amount,
        float $beforeBalance,
        float $afterBalance
    ): bool {
        return self::create([
            'merchant_id' => $merchantId,
            'fund_flow_type' => $type,
            'order_no' => $orderNo,
            'fund_flow_amount' => $amount,
            'balance_before' => $beforeBalance,
            'balance_after' => $afterBalance,
            'fund_flow_time' => time()
        ]) ? true : false;
    }

    // 获取指定时间范围内的资金流水
    public static function getFlowsByDateRange(int $merchantId, string $startDate, string $endDate)
    {
        return self::where('merchant_id', $merchantId)
            ->whereBetweenTime('create_time', $startDate, $endDate)
            ->order('id', 'desc')
            ->select();
    }
} 